package problem394;

//394.字符串解码
//https://leetcode.cn/problems/decode-string/description/

import java.util.Stack;

class Solution {
    private static StringBuffer shift(int n, StringBuffer s) {
        StringBuffer ret = new StringBuffer();
        for(int i = 0; i<n; i++) {
            ret.append(s);
        }
        return ret;
    }
    public static String decodeString (String _s) {
        Stack<Integer> nums = new Stack<>();
        Stack<Character> stack = new Stack<>();
        int i = 0;
        char[] s = _s.toCharArray();
        while (i<s.length) {
            int ret = 0;
            while(i < s.length && s[i]>='0' && s[i] <='9') {
                ret = ret*10 + (s[i]-'0');
                i++;
            }
            if(ret!=0) nums.add(ret);
            stack.add(s[i]);
            if(s[i] == ']') {
                stack.pop(); //弹出 ]
                StringBuffer t = new StringBuffer();
                while (stack.peek()!='[') {
                    t.append(stack.pop());
                }
                stack.pop(); //弹出 [
                t.reverse();
                t = shift(nums.pop(), t);
                for(int j = 0; j<t.length(); j++) {
                    stack.add(t.charAt(j));
                }
            }
            i++;
        }
        StringBuffer ret = new StringBuffer();
        while (!stack.isEmpty()) {
            ret.append(stack.pop());
        }
        ret.reverse();
        return ret.toString();
    }
}